package com.asen.commons.core.jdbc.handler;

import com.asen.commons.utils.BaseAssert;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * list类型处理
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-13
 */
public class ListTypeHandler<T> implements TypeHandler<List<T>> {

    private Class<T> type;

    public ListTypeHandler(Class<T> type) {
        BaseAssert.notNull(type, "参数type不能为空");
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, List<T> parameter) throws Exception {

    }

    @Override
    public List<T> getResult(ResultSet rs, String columnName) throws Exception {
        return null;
    }

    @Override
    public List<T> getResult(ResultSet rs, int columnIndex) throws Exception {
        return null;
    }

    @Override
    public List<T> getResult(CallableStatement cs, int columnIndex) throws Exception {
        return null;
    }

    @Override
    public int getSqlType() {
        return 0;
    }

    @Override
    public String toSqlValue(Object value) throws Exception {
        return null;
    }

    @Override
    public List<T> getValue(Object value) throws Exception {

        if (value == null) {
            return null;
        }

        List list = new ArrayList<>();

        // 非集合类型的处理
        if (!(value instanceof List<?>)) {
            TypeHandler handler = TypeHandlerHolder.getHandler(type);
            if (handler == null) {
                return null;
            }

            Object obj = handler.getValue(value);
            list.add(obj);
            return list;
        }

        for (Object entry : (List) value) {
            TypeHandler handler = TypeHandlerHolder.getHandler(type);
            if (handler == null) {
                continue;
            }
            Object obj = handler.getValue(entry);
            list.add(obj);
        }

        return list;
    }

}
